const router = require("koa-router")();
const result = require("../../config/result");
const {
  getToken,
  addUrl,
  whereUrl,
  updateUrl,
} = require("../../config/databaseapi");
const {
  regCheck,
  shopInfor,
  categoryCheck,
  unitCheck,
  dishCheck,
} = require("../../config/checking");
const { Auth } = require("../../token/auth");
const { upload, cosfun } = require("../../cos/cos");
const moment = require("moment");
moment.locale("zh-cn");
//获取订单接口哦
router.get('/obtainorder',new Auth().m , async ctx => {
    let {page,transac_status} = ctx.query
    let sk = Number(page)*10
    let par = {}
    if (transac_status != '') {
        par['transac_status'] = transac_status
    }else{
        delete par.transac_status
    }
    let OBJ = JSON.stringify(par)
    let query = `db.collection('order').where(${OBJ}).orderBy('ordertime','desc').field({menu:false}).limit(10).skip(${sk}).get()`
    try {
        const res =  await new getToken().posteve(whereUrl,query)
        const data = res.data.map(item => {
            return JSON.parse(item)
        })
        let total = {total : res.pager.Total }
        const arr = {...{result:data},...total}
        new result(ctx,'SUCCESS',200,arr).answer()
    } catch (error) {
        new result(ctx,'服务器发生错误',500).answer()
    }
})
//获取详细菜单接口
router.get('/vieworder', new Auth().m , async ctx =>{
    let {id} = ctx.query
    let query = `db.collection('order').doc('${id}').field({menu:true}).get()`
    try {
        const res = await new getToken().posteve(whereUrl,query)
        const data = res.data.map(item => {
            return JSON.parse(item)
        })
        new result(ctx,'SUCCESS',200,data[0]).answer()
    } catch (error) {
        new result(ctx,'服务器发生错误',500).answer()
        
    }
})
//接单
router.get('/receiving', new Auth().m , async ctx =>{
    let {id} = ctx.query
    let query = `db.collection('order').doc('${id}').update({data:{recstatus:'rec_order'}})`
    try {
        await new getToken().posteve(updateUrl,query)
        new result(ctx,'SUCCESS',200).answer()
    } catch (error) {
        new result(ctx,'服务器发生错误',500).answer()
    }
})
//结账
router.get('/checkout',new Auth().m ,async ctx => {
    let {id,openid,totalamount,ordernum} = ctx.query
    let subData = {
        'name1': {'value' : '立茶'},
        'character_string2':{'value' : ordernum},
        'amount5':{'value' : totalamount}
        
    }
    let query = `db.collection('order').doc('${id}').update({data:{transac_status:'success'}})`
    try {
        await new getToken().subscribe(openid,subData)
        await new getToken().posteve(updateUrl,query)
        new result(ctx,'下单成功',200).answer()
    } catch (error) {
        new result(ctx,'服务器错误请重试',500).answer()
    }
})
module.exports = router.routes();